﻿#region Copyright
/* © 2008 George Tsiokos, licensed under the Microsoft Reciprocal License (Ms-RL) */
#endregion
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;

namespace Comet.Net.Interop {
    internal static class Kernel32 {

		#region Fields (1) 
        /// <summary>From WINNT.H.</summary>
        private const int DUPLICATE_SAME_ACCESS = 0x00000002;

		#endregion Fields 

        /// <summary>
        /// Returns a duplicated WaitHandle
        /// </summary>
        /// <exception cref="InvalidOperationException">DuplicateHandle returned false</exception>
        public static WaitHandle DuplicateHandle (SafeWaitHandle sourceWaitHandle) {
            SafeWaitHandle newHandle;

            IntPtr currentProcess = GetCurrentProcess ();
            bool result = DuplicateHandle (
                                    currentProcess,
                                    sourceWaitHandle.DangerousGetHandle (),
                                    currentProcess,
                                    out newHandle,
                                    0,
                                    false,
                                    DUPLICATE_SAME_ACCESS);
            if (!result)
                throw new InvalidOperationException ();

            return new EncapsulatedHandle (newHandle);
        }

		#region Methods (2) 


		// Private Methods (2) 

        [DllImport ("kernel32.dll")]
        private static extern bool DuplicateHandle (
            IntPtr hSourceProcessHandle,
            IntPtr hSourceHandle,
            IntPtr hTargetProcessHandle,
            out SafeWaitHandle lpTargetHandle,
            uint dwDesiredAccess,
            bool bInheritHandle,
            uint dwOptions);

        [DllImport ("kernel32.dll")]
        private static extern IntPtr GetCurrentProcess ();


		#endregion Methods 

    }
}
